﻿using System;
using System.Collections.Generic;

using Argotic.Syndication;
using Argotic.Common;

namespace RSS_Downloader
{
    static class Tools
    {
        public static string ToHumanString(this long Bytes)
        {
            if (Bytes >= 1073741824)
            {
                Decimal size = Decimal.Divide(Bytes, 1073741824);
                return String.Format("{0:##.##} GB", size);
            }
            else if (Bytes >= 1048576)
            {
                Decimal size = Decimal.Divide(Bytes, 1048576);
                return String.Format("{0:##.##} MB", size);
            }
            else if (Bytes >= 1024)
            {
                Decimal size = Decimal.Divide(Bytes, 1024);
                return String.Format("{0:##.##} KB", size);
            }
            else if (Bytes > 0 & Bytes < 1024)
            {
                Decimal size = Bytes;
                return String.Format("{0:##.##} Bytes", size);
            }
            else
            {
                return "0 Bytes";
            }
        }


        public static IEnumerable<MediaFile> GetAllFilesFrom(Uri uri)
        {
            SyndicationResourceLoadSettings settings = new SyndicationResourceLoadSettings();
            settings.AutoDetectExtensions = true;

            GenericSyndicationFeed feed = GenericSyndicationFeed.Create(uri, settings);

            switch (feed.Format)
            {
                case SyndicationContentFormat.Atom:
                    AtomFeed atomFeed = feed.Resource as AtomFeed;
                    if (atomFeed != null)
                        foreach (AtomEntry atomEntry in atomFeed.Entries)
                            foreach (AtomLink atomLink in atomEntry.Links)
                                yield return new MediaFile(atomFeed.Title.Content, atomLink.Uri, atomLink.Length);
                    break;

                case SyndicationContentFormat.Rss:
                    RssFeed rssFeed = feed.Resource as RssFeed;
                    if (rssFeed != null)
                        foreach (RssItem rssItem in rssFeed.Channel.Items)
                            foreach (RssEnclosure rssEnclosure in rssItem.Enclosures)
                                yield return new MediaFile(rssFeed.Channel.Title, rssEnclosure.Url, rssEnclosure.Length);
                    break;
                default:
                    throw new ArgumentException("Unknown Feed Type");
            }
        }
    }
}
